package online.chazi.bootplus.commons.utils.natives;

import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.servlet.http.HttpServletRequest;

/**
 * 说明：UCloud云提供的ulb（负载均衡）会把用户真实ip带到header中。
 * 本工具用以提取该ip
 * Created by 叉子同学 on 2020-04-10 17:29
 */
public class UCloudIpHelper {

    public static String getRemoteAddr(ServerHttpRequest serverHttpRequest) {
        return getRemoteAddr((HttpServletRequest) serverHttpRequest);
    }

    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("X_FORWARDED_FOR");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        if (ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip)) {
            int i = ip.indexOf(',');
            if (i > 7) {
                return ip.substring(0, i);
            } else {
                return ip;
            }
        }

        ip = request.getHeader("X-Real-IP");
        if (ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getHeader("Proxy-Client-IP");
        if (ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getHeader("WL-Proxy-Client-IP");
        if (ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getHeader("HTTP_CLIENT_IP");
        if (ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        return request.getRemoteAddr();
    }

}
